package com.andaily.hb.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

/**
 * 2024/1/7 22:58
 *
 * @author Shengzhao Li
 * @since 3.0.0
 */
public class UdpServer {

    private static final Logger LOG = LoggerFactory.getLogger(UdpServer.class);


    private boolean running;


    private final int port;

    public UdpServer(int port) {
        this.port = port;
    }

    public int getPort() {
        return port;
    }

    public void start() {
        LOG.info("UDP Server prepare....");
        try (DatagramChannel channel = DatagramChannel.open()) {
            channel.socket().bind(new InetSocketAddress(port));
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            running = true;
            LOG.info("UDP Server is running on port {}", port);
            while (running) {
                buffer.clear();
                InetSocketAddress clientAddress = (InetSocketAddress) channel.receive(buffer);
                buffer.flip();
                byte[] data = new byte[buffer.limit()];
                buffer.get(data);
                LOG.info("Received from client: {} : {}", clientAddress, new String(data));

                // Echo back to the client
                channel.send(ByteBuffer.wrap("OK!".getBytes()), clientAddress);
            }
        } catch (IOException e) {
            LOG.error("Udp-Server error", e);
        }
    }


    public void stop() {
        running = false;
        LOG.info("UDP Server is stop, running:{}", running);
    }
}
